/*
 *  UserSettingsDialog.java
 *
 *  Course Project for User Interface Programming I, 2011
 *  Group 19
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or any later version.
 *
 */
package justdoit.view;

import justdoit.view.model.LanguagesComboBoxModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicBorders.ButtonBorder;
import javax.swing.plaf.basic.BasicBorders.FieldBorder;
import justdoit.Startup;
import justdoit.controller.TaskManager;
import justdoit.model.User;
import justdoit.controller.LanguageManager;
//import justdoit.model.Password;
import justdoit.controller.ThemeManager;
import justdoit.view.model.ThemeComboBoxModel;

/**
 * This is class is for displaying User Settings Dialog/Window
 * where user can change settings like Language, Color, Theme, etc
 * of the program
 *
 * @author shadone & Can
 */
public class UserSettingsDialog extends JDialog {

    private final int width = 250;
    private final int height = 300;
    private String newTheme;
    private String oldTheme;
    private boolean themeChange = false;
    private User user;
    // components
    private JPanel infoPanel;
    private JPanel inputPanel;
    private JPanel messagePanel;
    private JLabel messageLabel;
    private JPanel actionPanel;
    private JLabel userNameLabel;
    private JTextField userNameInput;
    private JLabel oldPasswordLabel;
    private JLabel newPasswordLabel;
    private JPasswordField oldPasswordInput;
    private JPasswordField newPasswordInput;
    private JLabel languageLabel;
    private JComboBox languageComboBox;
    private JButton changeColorButton;
    private JComboBox themeComboBox = new JComboBox();
    private Color color = Color.lightGray;
    private JButton okButton;
    private JButton cancelButton;
    private JCheckBox autoloadCheckBox; //added by Can
    // ActionListeners
    private ActionListener cancelAL;
    private ActionListener okAL;
    private ActionListener languageAL;
    private ActionListener themeAL;
    private ActionListener colorAL;

    public UserSettingsDialog(User currentUser) {
        this.user = currentUser;
        initComponents();
    }

    // to initialize the action listeners
    public void initActionListeners() {
        cancelAL = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (themeChange == true && oldTheme != null) {
                    ThemeManager.setTheme(oldTheme);
                }
                UserSettingsDialog.this.dispose();
            }
        };

        okAL = new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                // password should come first, as it needs some validation
                char[] oldPassword = oldPasswordInput.getPassword();
                char[] newPassword = newPasswordInput.getPassword();
                if (oldPassword.length != 0 || newPassword.length != 0) {
                    if (user.matchPassword(oldPassword)) {
                        user.setPassword(newPassword);
                    } else {
                        System.out.print("Please enter the correct old password!");
                        oldPasswordInput.setBorder(new ButtonBorder(Color.orange, Color.red, Color.red, Color.yellow));
                        oldPasswordInput.requestFocus();
                        oldPasswordInput.selectAll();
                        // TODO: Dilshod, say something here. :)
                        showMessage("");
                        return;
                    }
                }
                // theme
                if (themeChange == true) {
                    user.setTheme(newTheme);
                    ThemeManager.setTheme(newTheme);
                }
                // username
                user.setUserName(userNameInput.getText().trim());
                // locale
                Locale oldLocale = user.getLocale();
                user.setLocale(((LanguagesComboBoxModel) languageComboBox.getModel()).getSelectedLocale());
                // auto login
                if (autoloadCheckBox.getSelectedObjects() == null) {
                    System.out.println("autoload is NOT selected!");
                    Startup.getDs().setUserName("");
                } else {
                    Startup.getDs().setUserName(user.getUserName());
                }
                // update it in database
                if (TaskManager.updateUser(user) < 0) {
                    System.out.println("Update user failed!");
                } else {
                    UserSettingsDialog.this.dispose();
                    Startup.getMainFrame().updateUserNameLabel();
                    if (!user.getLocale().equals(oldLocale)) {
                        if (LanguageManager.loadLanguage(user.getLocale()) < 0) {
                            System.out.println("Load new language error!");
                        } else {
                            System.out.println("Language changed to :" + user.getLocale().getDisplayName());
                            Startup.getMainFrame().dispose();
                            Startup.showMainFrame(user);
                        }
                    }
                }
            }
        };

        themeAL = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                ThemeComboBoxModel themeModel =
                        (ThemeComboBoxModel) ((JComboBox) e.getSource()).getModel();
                newTheme = themeModel.getSelectedTheme();
                themeChange = true;
                ThemeManager.setTheme(newTheme);
            }
        };

        colorAL = new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                UIManager.put("ColorChooser.okText", LanguageManager.getString("button.ok"));
                UIManager.put("ColorChooser.cancelText", LanguageManager.getString("button.cancel"));
                UIManager.put("ColorChooser.resetText", LanguageManager.getString("button.reset"));
                UIManager.put("ColorChooser.swatchesNameText", LanguageManager.getString("swatches"));
                UIManager.put("ColorChooser.swatchesRecentText", LanguageManager.getString("recent"));
                UIManager.put("ColorChooser.previewText", LanguageManager.getString("preview"));
                UIManager.put("ColorChooser.sampleText", LanguageManager.getString("sampleText"));
                UIManager.put("ColorChooser.hsbNameText", LanguageManager.getString("hsb"));
                UIManager.put("ColorChooser.hsbHueText", LanguageManager.getString("hue"));
                UIManager.put("ColorChooser.hsbSaturationText", LanguageManager.getString("saturation"));
                UIManager.put("ColorChooser.hsbBrightnessText", LanguageManager.getString("brightness"));
                UIManager.put("ColorChooser.hsbRedText", LanguageManager.getString("hsbRed"));
                UIManager.put("ColorChooser.hsbGreenText", LanguageManager.getString("hsbGreen"));
                UIManager.put("ColorChooser.hsbBlueText", LanguageManager.getString("hsbBlue"));
                UIManager.put("ColorChooser.rgbNameText", LanguageManager.getString("rgb"));
                UIManager.put("ColorChooser.rgbRedText", LanguageManager.getString("rgbRed"));
                UIManager.put("ColorChooser.rgbGreenText", LanguageManager.getString("rgbGreen"));
                UIManager.put("ColorChooser.rgbBlueText", LanguageManager.getString("rgbBlue"));

                color = JColorChooser.showDialog(UserSettingsDialog.this,
                        LanguageManager.getString("title.changeColor"), color);

                if (color != null) {
                    inputPanel.setBackground(color);
                    actionPanel.setBackground(color);
                    MainFrame mf = Startup.getMainFrame();
                    mf.updateColor(color);
                    //taskWindow.setBackgroundColor(color);
                }
            }
        };
    }

    // modified by Can
    private void initComponents() {
        initActionListeners();
        // user name
        userNameLabel = new JLabel(LanguageManager.getString("label.username"));
        userNameInput = new JTextField(user.getUserName(), 10);
        userNameInput.setToolTipText(LanguageManager.getString("tooltip.username"));
        oldPasswordLabel = new JLabel(LanguageManager.getString("label.oldPassword"));
        oldPasswordLabel.setToolTipText(LanguageManager.getString("tooltip.oldPassword"));
        newPasswordLabel = new JLabel(LanguageManager.getString("label.password"));
        newPasswordLabel.setToolTipText(LanguageManager.getString("tooltip.newPassword"));
        oldPasswordInput = new JPasswordField();
        oldPasswordInput.setToolTipText(LanguageManager.getString("tooltip.oldPassword"));
        newPasswordInput = new JPasswordField();
        newPasswordInput.setToolTipText(LanguageManager.getString("tooltip.newPassword"));
        changeColorButton = new JButton(LanguageManager.getString("label.changeColor"));
        changeColorButton.setToolTipText(LanguageManager.getString("tooltip.changeColor"));
        okButton = new JButton(LanguageManager.getString("button.ok"));
        cancelButton = new JButton(LanguageManager.getString("button.cancel"));
        // language
        languageLabel = new JLabel(LanguageManager.getString("label.language"));
        languageComboBox = new JComboBox();
        languageComboBox.setToolTipText(LanguageManager.getString("tooltip.language"));
        languageComboBox.setModel(new LanguagesComboBoxModel(LanguageManager.getAvailableLocales()));
        if (languageComboBox.getItemCount() > 0) {
            languageComboBox.setSelectedItem(user.getLocale().getDisplayName());
        }

        autoloadCheckBox = new JCheckBox(LanguageManager.getString("label.autoLogin"));
        autoloadCheckBox.setToolTipText(LanguageManager.getString("tooltip.autoLogin"));
        autoloadCheckBox.setSize(245, autoloadCheckBox.getHeight());
        themeComboBox.setModel(new ThemeComboBoxModel());
        themeComboBox.setToolTipText(LanguageManager.getString("tooltip.theme"));
        if (user.getTheme() != null && user.getTheme() != "") {
            this.oldTheme = user.getTheme();
            themeComboBox.setSelectedItem(user.getDisplayTheme());
        }

        inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(6, 2, 10, 10));
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        inputPanel.add(userNameLabel);
        inputPanel.add(userNameInput);
        inputPanel.add(oldPasswordLabel);
        inputPanel.add(oldPasswordInput);
        inputPanel.add(newPasswordLabel);
        inputPanel.add(newPasswordInput);
        inputPanel.add(languageLabel);
        inputPanel.add(languageComboBox);
        inputPanel.add(changeColorButton);
        inputPanel.add(themeComboBox);
        inputPanel.add(autoloadCheckBox);
        if (Startup.getDs().getUserName() != null && Startup.getDs().getUserName() != "") {
            autoloadCheckBox.setSelected(true);
        } else {
            autoloadCheckBox.setSelected(false);
        }

        actionPanel = new JPanel();
        actionPanel.setLayout(new FlowLayout());
        actionPanel.add(okButton);
        actionPanel.add(cancelButton);

        cancelButton.addActionListener(cancelAL);
        okButton.addActionListener(okAL);
        languageComboBox.addActionListener(languageAL);
        changeColorButton.addActionListener(colorAL);
        themeComboBox.addActionListener(themeAL);

        // message panel
        messageLabel = new JLabel("");
        messageLabel.setSize(width, 10);
        messageLabel.setForeground(Color.red);
        messagePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        messagePanel.add(messageLabel);

        // info panel
        infoPanel = new JPanel(new BorderLayout());
        infoPanel.add(BorderLayout.CENTER, inputPanel);
        infoPanel.add(BorderLayout.SOUTH, messagePanel);

        this.setLayout(new BorderLayout());
        this.add(BorderLayout.CENTER, infoPanel);
        this.add(BorderLayout.SOUTH, actionPanel);

        this.getRootPane().setDefaultButton(okButton);

        // Hide on Close
        this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        this.setSize(width, height);
        this.setTitle(LanguageManager.getString("title.userSettings"));
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setModal(true);
    }

    protected void showMessage(String message) {
        this.messageLabel.setText(message);
    }
}
